package com.way.cloud.common.nacos;

import com.alibaba.cloud.nacos.NacosConfigAutoConfiguration;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration;
import com.way.cloud.common.nacos.factory.YamlPropertySourceFactory;
import com.way.cloud.common.nacos.properties.NacosProperties;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@EnableConfigurationProperties(NacosProperties.class)
@ConditionalOnClass({NacosDiscoveryProperties.class, NacosConfigProperties.class})
@AutoConfigureBefore({NacosDiscoveryAutoConfiguration.class, NacosConfigAutoConfiguration.class, AutoServiceRegistrationAutoConfiguration.class})
@PropertySource(value = "classpath:config/application.yml", encoding = "UTF-8", factory = YamlPropertySourceFactory.class)
public class NacosAutoConfiguration {

    @Resource
    private NacosProperties props;

    @Bean
    @ConditionalOnMissingBean
    public NacosDiscoveryProperties nacosDiscoveryProperties() {
        NacosDiscoveryProperties properties = new NacosDiscoveryProperties();
        properties.setServerAddr(props.getServerAddr());
        properties.setNamespace(props.getNamespace());
        properties.setGroup(props.getGroup());
        return properties;
    }

    @Bean
    @ConditionalOnMissingBean
    public NacosConfigProperties nacosConfigProperties() {
        NacosConfigProperties properties = new NacosConfigProperties();
        properties.setServerAddr(props.getServerAddr());
        properties.setNamespace(props.getNamespace());
        properties.setGroup(props.getGroup());
        return properties;
    }

}
